const vscode = require('vscode');
const path = require('path');
const fs = require('fs');

/**
 * Context Engine Webview 视图提供器
 * 管理侧边栏面板的 Webview 界面
 */
class ContextEngineViewProvider {
    constructor(context) {
        this.context = context;
        this._view = undefined;
        this.history = this.loadHistory();
        
        // 监听编辑器变化（简化版本，只需要更新历史记录）
        vscode.window.onDidChangeActiveTextEditor(() => {
            // 可以在这里添加需要的更新逻辑
        });
    }

    /**
     * 解析 Webview 视图
     */
    resolveWebviewView(webviewView, context, token) {
        console.log('ContextHelper: resolveWebviewView called');
        this._view = webviewView;

        webviewView.webview.options = {
            enableScripts: true,
            localResourceRoots: [
                vscode.Uri.joinPath(this.context.extensionUri, 'src'),
                vscode.Uri.joinPath(this.context.extensionUri, 'media')
            ]
        };

        try {
            webviewView.webview.html = this.getHtmlForWebview(webviewView.webview);
            console.log('ContextHelper: HTML set successfully');
        } catch (error) {
            console.error('ContextHelper: Error setting HTML:', error);
        }

        // 处理来自 Webview 的消息
        webviewView.webview.onDidReceiveMessage(async (message) => {
            try {
                await this.handleMessage(message);
            } catch (error) {
                console.error('ContextHelper: Error handling message:', error);
            }
        });

        // 初始化界面数据
        try {
            this.updateHistory();
            console.log('ContextHelper: History updated successfully');
        } catch (error) {
            console.error('ContextHelper: Error updating history:', error);
        }
    }

    /**
     * 处理来自 Webview 的消息
     */
    async handleMessage(message) {
        switch (message.type) {
            case 'generateContext':
                await this.handleGenerateContext(message.data);
                break;
            case 'selectRange':
                await this.handleSelectRange(message.data.rangeType);
                break;
            case 'clearHistory':
                this.clearHistory();
                break;
            case 'loadHistoryItem':
                await this.loadHistoryItem(message.data.index);
                break;
            case 'getFileList':
                await this.sendFileList(message.data.query, message.data.excludeFiles);
                break;
            case 'getSymbolList':
                await this.sendSymbolList(message.data.query);
                break;
            case 'ready':
                // Webview 已准备就绪，发送初始数据
                this.updateHistory();
                break;
        }
    }

    /**
     * 处理生成上下文的请求
     */
    async handleGenerateContext(data) {
        try {
            const { prompt, fileReferences: frontendFileRefs, symbolReferences: frontendSymbolRefs } = data;

            if (!prompt || prompt.trim() === '') {
                this.showMessage('error', '请输入提示内容。');
                return;
            }

            // 优先使用前端发送的引用信息，如果没有则从文本中提取
            let fileReferences = frontendFileRefs && frontendFileRefs.length > 0
                ? frontendFileRefs
                : this.extractFileReferences(prompt);
            let symbolReferences = frontendSymbolRefs && frontendSymbolRefs.length > 0
                ? frontendSymbolRefs
                : this.extractSymbolReferences(prompt);
            let contextContent;
            let historyInfo;

            if (fileReferences.length > 0) {
                // 如果有文件引用，直接使用引用的文件
                contextContent = await this.generateContextContent(null, null, prompt, fileReferences, symbolReferences);
                historyInfo = {
                    timestamp: new Date().toISOString(),
                    fileName: `${fileReferences.length} 个文件`,
                    rangeType: 'multi-file',
                    prompt: prompt,
                    codePreview: `引用文件: ${fileReferences.join(', ')}`,
                    fileReferences: fileReferences,
                    symbolReferences: symbolReferences
                };
            } else {
                // 如果没有文件引用，尝试使用当前编辑器
                const editor = vscode.window.activeTextEditor;
                if (!editor) {
                    this.showMessage('error', '请在提示中使用 @filename 引用文件，或先打开一个文件。');
                    return;
                }

                // 默认使用整个文件，如果有选中文本则使用选中文本
                const rangeType = editor.selection.isEmpty ? 'file' : 'selection';
                const selectedRange = await this.getCodeRange(editor, rangeType);
                if (!selectedRange) {
                    this.showMessage('error', '无法获取代码范围。');
                    return;
                }

                contextContent = await this.generateContextContent(editor, selectedRange, prompt, fileReferences, symbolReferences);
                historyInfo = {
                    timestamp: new Date().toISOString(),
                    fileName: path.basename(editor.document.fileName),
                    rangeType: rangeType,
                    prompt: prompt,
                    codePreview: selectedRange.text.substring(0, 200) + (selectedRange.text.length > 200 ? '...' : ''),
                    fileReferences: fileReferences,
                    symbolReferences: symbolReferences
                };
            }

            // 保存到历史记录
            this.addToHistory(historyInfo);

            // 生成上下文文件
            await this.generateContextFile(contextContent);

            this.showMessage('success', '上下文文件已生成！');

        } catch (error) {
            console.error('生成上下文时出错:', error);
            this.showMessage('error', `生成失败: ${error.message}`);
        }
    }

    /**
     * 获取代码范围
     */
    async getCodeRange(editor, rangeType) {
        const document = editor.document;
        const config = vscode.workspace.getConfiguration('copilotAgentBridge');
        const maxLines = config.get('maxFileSize', 10000);

        let range, text;

        switch (rangeType) {
            case 'file':
                range = new vscode.Range(0, 0, document.lineCount - 1, document.lineAt(document.lineCount - 1).text.length);
                text = document.getText(range);
                if (document.lineCount > maxLines) {
                    const truncatedRange = new vscode.Range(0, 0, maxLines - 1, document.lineAt(maxLines - 1).text.length);
                    text = document.getText(truncatedRange) + `\n\n... (文件在 ${maxLines} 行处被截断。总行数: ${document.lineCount})`;
                    range = truncatedRange;
                }
                break;

            case 'selection':
                if (editor.selection.isEmpty) {
                    return null;
                }
                range = editor.selection;
                text = document.getText(range);
                break;

            default:
                return null;
        }

        return { type: rangeType, range, text };
    }

    /**
     * 生成上下文内容
     */
    async generateContextContent(editor, selectedRange, userPrompt, fileReferences = null, symbolReferences = null) {
        const config = vscode.workspace.getConfiguration('contextEngine');
        const template = config.get('promptTemplate', '请分析以下代码：\n\n{code}\n\n{prompt}');
        const includeMetadata = config.get('includeMetadata', true);
        const fileSeparator = config.get('fileSeparator', '\n\n================================================================================\n\n');

        // 使用传入的引用信息，如果没有则从文本中解析
        const actualFileReferences = fileReferences || this.extractFileReferences(userPrompt);
        const actualSymbolReferences = symbolReferences || this.extractSymbolReferences(userPrompt);

        let codeContent = '';

        if (actualFileReferences.length > 0) {
            // 如果有文件引用，收集所有引用文件的内容
            codeContent = await this.collectReferencedFilesContent(actualFileReferences, includeMetadata, fileSeparator);
        } else if (editor && selectedRange) {
            // 如果没有文件引用但有编辑器和选择范围，使用当前选择的代码范围
            const document = editor.document;
            const fileName = path.basename(document.fileName);
            const language = document.languageId;

            if (includeMetadata) {
                const contextInfo = [
                    `文件: ${fileName}`,
                    `语言: ${language}`,
                    `范围: ${this.getRangeDescription(selectedRange)}`,
                    `行数: ${selectedRange.range.start.line + 1}-${selectedRange.range.end.line + 1}`,
                    `时间戳: ${new Date().toISOString()}`,
                    ''
                ].join('\n');
                codeContent = contextInfo;
            }

            codeContent += `\`\`\`${language}\n${selectedRange.text}\n\`\`\``;
        } else {
            // 既没有文件引用也没有编辑器，返回空内容
            codeContent = '// 没有可用的代码内容';
        }

        // 处理符号引用
        if (actualSymbolReferences.length > 0) {
            const symbolContent = await this.collectSymbolContent(editor, actualSymbolReferences, includeMetadata);
            if (symbolContent) {
                codeContent += fileSeparator + symbolContent;
            }
        }

        let content = template
            .replace('{code}', codeContent)
            .replace('{prompt}', userPrompt || '');

        return content;
    }

    /**
     * 提取文件引用
     */
    extractFileReferences(text) {
        const fileRegex = /@([^\s@#]+)/g;
        const matches = [];
        let match;

        while ((match = fileRegex.exec(text)) !== null) {
            matches.push(match[1]);
        }

        return [...new Set(matches)]; // 去重
    }

    /**
     * 提取符号引用
     */
    extractSymbolReferences(text) {
        const symbolRegex = /#([^\s@#]+)/g;
        const matches = [];
        let match;

        while ((match = symbolRegex.exec(text)) !== null) {
            matches.push(match[1]);
        }

        return [...new Set(matches)]; // 去重
    }

    /**
     * 收集引用文件的内容
     */
    async collectReferencedFilesContent(fileReferences, includeMetadata, fileSeparator) {
        const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
        if (!workspaceFolder) {
            return '错误：未找到工作区';
        }

        const config = vscode.workspace.getConfiguration('contextEngine');
        const maxFileSize = config.get('maxFileSize', 10000);
        const fileContents = [];

        for (const fileName of fileReferences) {
            try {
                // 查找文件
                const files = await vscode.workspace.findFiles(`**/${fileName}`, '**/node_modules/**');

                if (files.length === 0) {
                    fileContents.push(`错误：未找到文件 ${fileName}`);
                    continue;
                }

                // 使用第一个匹配的文件
                const fileUri = files[0];
                const document = await vscode.workspace.openTextDocument(fileUri);
                const relativePath = vscode.workspace.asRelativePath(fileUri);

                let content = '';

                if (includeMetadata) {
                    content += [
                        `文件: ${fileName}`,
                        `路径: ${relativePath}`,
                        `语言: ${document.languageId}`,
                        `行数: ${document.lineCount}`,
                        `大小: ${document.getText().length} 字符`,
                        ''
                    ].join('\n');
                }

                // 获取文件内容
                let fileText = document.getText();

                // 如果文件太大，进行截断
                if (document.lineCount > maxFileSize) {
                    const lines = fileText.split('\n');
                    fileText = lines.slice(0, maxFileSize).join('\n');
                    fileText += `\n\n... (文件在 ${maxFileSize} 行处被截断。总行数: ${document.lineCount})`;
                }

                content += `\`\`\`${document.languageId}\n${fileText}\n\`\`\``;
                fileContents.push(content);

            } catch (error) {
                fileContents.push(`错误：无法读取文件 ${fileName}: ${error.message}`);
            }
        }

        return fileContents.join(fileSeparator);
    }

    /**
     * 收集符号内容
     */
    async collectSymbolContent(editor, symbolReferences, includeMetadata) {
        try {
            const document = editor.document;
            const symbols = await vscode.commands.executeCommand(
                'vscode.executeDocumentSymbolProvider',
                document.uri
            );

            if (!symbols) {
                return null;
            }

            const foundSymbols = [];
            const extractSymbols = (symbolList, parentName = '') => {
                for (const symbol of symbolList) {
                    const fullName = parentName ? `${parentName}.${symbol.name}` : symbol.name;

                    if (symbolReferences.some(ref =>
                        symbol.name.toLowerCase().includes(ref.toLowerCase()) ||
                        fullName.toLowerCase().includes(ref.toLowerCase())
                    )) {
                        const symbolText = document.getText(symbol.range);
                        foundSymbols.push({
                            name: symbol.name,
                            fullName: fullName,
                            kind: vscode.SymbolKind[symbol.kind],
                            text: symbolText,
                            range: symbol.range
                        });
                    }

                    if (symbol.children && symbol.children.length > 0) {
                        extractSymbols(symbol.children, fullName);
                    }
                }
            };

            extractSymbols(symbols);

            if (foundSymbols.length === 0) {
                return null;
            }

            let content = '';
            if (includeMetadata) {
                content += `符号引用 (${foundSymbols.length} 个):\n\n`;
            }

            foundSymbols.forEach((symbol, index) => {
                if (includeMetadata) {
                    content += [
                        `符号: ${symbol.name}`,
                        `类型: ${symbol.kind}`,
                        `完整名称: ${symbol.fullName}`,
                        `行数: ${symbol.range.start.line + 1}-${symbol.range.end.line + 1}`,
                        ''
                    ].join('\n');
                }

                content += `\`\`\`${document.languageId}\n${symbol.text}\n\`\`\``;

                if (index < foundSymbols.length - 1) {
                    content += '\n\n' + '-'.repeat(40) + '\n\n';
                }
            });

            return content;

        } catch (error) {
            return `错误：无法获取符号信息: ${error.message}`;
        }
    }

    /**
     * 获取范围描述
     */
    getRangeDescription(selectedRange) {
        switch (selectedRange.type) {
            case 'file': return '整个文件';
            case 'selection': return '选中文本';
            default: return '未知范围';
        }
    }

    /**
     * 生成上下文文件
     */
    async generateContextFile(contextContent) {
        try {
            // 创建 data 目录（如果不存在）
            const dataDir = this.getDataDirectory();
            if (!fs.existsSync(dataDir)) {
                fs.mkdirSync(dataDir, { recursive: true });
            }

            // 创建上下文文件
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            const contextFilePath = path.join(dataDir, `context-${timestamp}.txt`);

            // 写入内容到文件
            fs.writeFileSync(contextFilePath, contextContent, 'utf8');

            // 显示文件路径并提供复制选项
            const relativePath = path.relative(vscode.workspace.workspaceFolders?.[0]?.uri.fsPath || '', contextFilePath);

            const action = await vscode.window.showInformationMessage(
                `上下文文件已生成: ${relativePath}`,
                '复制路径',
                '打开文件',
                '打开文件夹'
            );

            switch (action) {
                case '复制路径':
                    await vscode.env.clipboard.writeText(contextFilePath);
                    vscode.window.showInformationMessage('文件路径已复制到剪贴板！');
                    break;
                case '打开文件':
                    const document = await vscode.workspace.openTextDocument(contextFilePath);
                    await vscode.window.showTextDocument(document);
                    break;
                case '打开文件夹':
                    await vscode.commands.executeCommand('revealFileInOS', vscode.Uri.file(contextFilePath));
                    break;
            }

        } catch (error) {
            console.error('生成上下文文件时出错:', error);
            throw error;
        }
    }

    /**
     * 获取 Microsoft Edge 可执行文件路径
     */
    async getEdgePath() {
        const config = vscode.workspace.getConfiguration('copilotAgentBridge');
        const configuredPath = config.get('edgePath', '');

        if (configuredPath && fs.existsSync(configuredPath)) {
            return configuredPath;
        }

        // 根据平台自动检测 Edge 路径
        const osModule = require('os');
        const platform = osModule.platform();
        const possiblePaths = [];

        if (platform === 'win32') {
            possiblePaths.push(
                'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
                'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
                path.join(osModule.homedir(), 'AppData\\Local\\Microsoft\\Edge\\Application\\msedge.exe')
            );
        } else if (platform === 'darwin') {
            possiblePaths.push(
                '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'
            );
        } else {
            possiblePaths.push(
                '/usr/bin/microsoft-edge',
                '/usr/bin/microsoft-edge-stable',
                '/opt/microsoft/msedge/msedge'
            );
        }

        for (const edgePath of possiblePaths) {
            if (fs.existsSync(edgePath)) {
                return edgePath;
            }
        }

        return null;
    }

    /**
     * 使用文件打开 Edge
     */
    async openEdgeWithFile(edgePath, filePath) {
        return new Promise((resolve, reject) => {
            // Copilot URL
            const copilotUrl = 'https://copilot.microsoft.com/';

            // 启动 Edge 并打开 Copilot
            const { spawn } = require('child_process');
            const edgeProcess = spawn(edgePath, [
                '--new-window',
                copilotUrl
            ], {
                detached: true,
                stdio: 'ignore'
            });

            edgeProcess.on('error', (error) => {
                reject(new Error(`启动 Edge 失败: ${error.message}`));
            });

            // 不等待 Edge 关闭
            edgeProcess.unref();

            // 给 Edge 启动时间，然后显示说明
            setTimeout(() => {
                vscode.window.showInformationMessage(
                    `Edge Copilot 已打开！请将文件拖拽到对话框: ${filePath}`,
                    '复制文件路径'
                ).then(selection => {
                    if (selection === '复制文件路径') {
                        vscode.env.clipboard.writeText(filePath);
                        vscode.window.showInformationMessage('文件路径已复制到剪贴板！');
                    }
                });
                resolve();
            }, 2000);
        });
    }



    /**
     * 显示消息
     */
    showMessage(type, message) {
        if (this._view) {
            this._view.webview.postMessage({
                type: 'showMessage',
                data: { type, message }
            });
        }
    }

    /**
     * 获取数据目录路径
     */
    getDataDirectory() {
        const config = vscode.workspace.getConfiguration('contextEngine');
        const customPath = config.get('outputPath', './data/');

        // 如果是绝对路径，直接使用
        if (path.isAbsolute(customPath)) {
            return customPath;
        }

        // 如果是相对路径，相对于工作区根目录
        const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
        if (workspaceFolder) {
            return path.resolve(workspaceFolder.uri.fsPath, customPath);
        }

        // 如果没有工作区，使用扩展的全局存储目录
        return path.join(this.context.globalStorageUri.fsPath, customPath);
    }

    /**
     * 加载历史记录
     */
    loadHistory() {
        try {
            const dataDir = this.getDataDirectory();
            const historyPath = path.join(dataDir, 'history.json');
            if (fs.existsSync(historyPath)) {
                const data = fs.readFileSync(historyPath, 'utf8');
                return JSON.parse(data);
            }
        } catch (error) {
            console.error('加载历史记录失败:', error);
        }
        return [];
    }

    /**
     * 保存历史记录
     */
    saveHistory() {
        try {
            const dataDir = this.getDataDirectory();
            // 确保目录存在
            if (!fs.existsSync(dataDir)) {
                fs.mkdirSync(dataDir, { recursive: true });
            }
            const historyPath = path.join(dataDir, 'history.json');
            fs.writeFileSync(historyPath, JSON.stringify(this.history, null, 2));
        } catch (error) {
            console.error('保存历史记录失败:', error);
        }
    }

    /**
     * 添加到历史记录
     */
    addToHistory(item) {
        this.history.unshift(item);
        // 限制历史记录数量
        if (this.history.length > 50) {
            this.history = this.history.slice(0, 50);
        }
        this.saveHistory();
        this.updateHistory();
    }

    /**
     * 清空历史记录
     */
    clearHistory() {
        this.history = [];
        this.saveHistory();
        this.updateHistory();
        this.showMessage('success', '历史记录已清空');
    }

    /**
     * 更新历史记录显示
     */
    updateHistory() {
        if (this._view) {
            this._view.webview.postMessage({
                type: 'updateHistory',
                data: this.history
            });
        }
    }

    /**
     * 加载历史记录项
     */
    async loadHistoryItem(index) {
        if (index >= 0 && index < this.history.length) {
            const item = this.history[index];
            this._view.webview.postMessage({
                type: 'loadHistoryItem',
                data: item
            });
        }
    }

    /**
     * 发送文件列表（@ 符号功能）
     */
    async sendFileList(query = '', excludeFiles = []) {
        try {
            const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
            if (!workspaceFolder) {
                this._view.webview.postMessage({
                    type: 'fileList',
                    data: []
                });
                return;
            }

            // 获取当前打开的文件
            const activeEditor = vscode.window.activeTextEditor;
            const activeFileName = activeEditor ? path.basename(activeEditor.document.fileName) : null;

            // 获取工作区中的所有文件
            const files = await vscode.workspace.findFiles(
                '**/*.{js,ts,jsx,tsx,py,java,cpp,c,h,cs,php,rb,go,rs,swift,kt,scala,dart,vue,html,css,scss,less,json,xml,yaml,yml,md}',
                '**/node_modules/**'
            );

            // 过滤和格式化文件列表
            let fileList = files
                .map(file => {
                    const relativePath = vscode.workspace.asRelativePath(file);
                    const fileName = path.basename(relativePath);
                    return {
                        name: fileName,
                        path: relativePath,
                        fullPath: file.fsPath,
                        isActive: fileName === activeFileName
                    };
                })
                .filter(file => {
                    // 排除已经引用的文件
                    if (excludeFiles.includes(file.name)) {
                        return false;
                    }

                    // 查询过滤
                    if (!query) return true;
                    const searchTerm = query.toLowerCase();
                    return file.name.toLowerCase().includes(searchTerm) ||
                           file.path.toLowerCase().includes(searchTerm);
                });

            // 排序：当前打开的文件优先，然后按名称排序
            fileList.sort((a, b) => {
                if (a.isActive && !b.isActive) return -1;
                if (!a.isActive && b.isActive) return 1;
                return a.name.localeCompare(b.name);
            });

            // 限制结果数量
            fileList = fileList.slice(0, 20);

            this._view.webview.postMessage({
                type: 'fileList',
                data: fileList
            });

        } catch (error) {
            console.error('获取文件列表失败:', error);
            this._view.webview.postMessage({
                type: 'fileList',
                data: []
            });
        }
    }

    /**
     * 发送符号列表（# 符号功能）
     */
    async sendSymbolList(query = '') {
        try {
            const editor = vscode.window.activeTextEditor;
            if (!editor) {
                this._view.webview.postMessage({
                    type: 'symbolList',
                    data: []
                });
                return;
            }

            // 获取当前文档的符号
            const symbols = await vscode.commands.executeCommand(
                'vscode.executeDocumentSymbolProvider',
                editor.document.uri
            );

            if (!symbols) {
                this._view.webview.postMessage({
                    type: 'symbolList',
                    data: []
                });
                return;
            }

            // 递归提取所有符号
            const extractSymbols = (symbolList, parentName = '') => {
                const result = [];
                for (const symbol of symbolList) {
                    const fullName = parentName ? `${parentName}.${symbol.name}` : symbol.name;
                    result.push({
                        name: symbol.name,
                        fullName: fullName,
                        kind: vscode.SymbolKind[symbol.kind],
                        range: symbol.range,
                        detail: symbol.detail || ''
                    });

                    // 递归处理子符号
                    if (symbol.children && symbol.children.length > 0) {
                        result.push(...extractSymbols(symbol.children, fullName));
                    }
                }
                return result;
            };

            const symbolList = extractSymbols(symbols)
                .filter(symbol => {
                    if (!query) return true;
                    const searchTerm = query.toLowerCase();
                    return symbol.name.toLowerCase().includes(searchTerm) ||
                           symbol.fullName.toLowerCase().includes(searchTerm);
                })
                .slice(0, 20); // 限制结果数量

            this._view.webview.postMessage({
                type: 'symbolList',
                data: symbolList
            });

        } catch (error) {
            console.error('获取符号列表失败:', error);
            this._view.webview.postMessage({
                type: 'symbolList',
                data: []
            });
        }
    }

    /**
     * 刷新面板
     */
    refresh() {
        this.updateHistory();
        this.showMessage('success', '面板已刷新');
    }

    /**
     * 获取 Webview HTML 内容
     */
    getHtmlForWebview(webview) {
        try {
            return this.getWebviewContent(webview);
        } catch (error) {
            console.error('ContextHelper: Error generating HTML content:', error);
            return `<!DOCTYPE html>
            <html>
            <head><title>ContextHelper</title></head>
            <body>
                <h1>ContextHelper</h1>
                <p>Error loading interface: ${error.message}</p>
            </body>
            </html>`;
        }
    }

    /**
     * 生成 Webview 内容
     */
    getWebviewContent(webview) {
        const styleUri = webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'media', 'style.css'));
        const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'media', 'script.js'));

        return `<!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Copilot Bridge</title>
            <link href="${styleUri}" rel="stylesheet">
        </head>
        <body>
            <div class="container">
                <!-- 头部区域 -->
                <div class="header">
                    <h2>⚡ Context Engine</h2>
                    <div class="author-info">
                        <span class="author-text">by TqCoder</span>
                    </div>
                </div>

                 <!-- 历史记录区域 -->
                <div class="section">
                    <div class="header history-header" id="historyHeader">
                        <h2>📊 生成历史</h2>
                        <button class="collapse-btn collapsed" id="collapseBtn">
                            <span class="collapse-icon">▼</span>
                        </button>
                    </div>
                    <div class="history-content collapsed" id="historyContent">
                        <div class="section-content">
                            <div class="history-list" id="historyList">
                                <div class="history-placeholder">
                                    暂无生成历史
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 智能上下文生成区域 -->
                <div class="section main-section">
                    <h3>🧠 智能上下文生成</h3>
                    <div class="section-content">
                        <!-- 引用标签区域 - 移到输入框外面上方 -->
                        <div class="reference-tags-outside" id="referenceTags">
                            <!-- 引用标签将在这里显示 -->
                        </div>

                        <!-- 输入容器 -->
                        <div class="input-container">
                            <textarea
                                id="promptInput"
                                class="prompt-input"
                                placeholder="描述你的需求，使用智能引用增强上下文...&#10;&#10;🔗 多文件引用：@file1.js @file2.js @config.json&#10;🎯 符号引用：#className #functionName #variableName&#10;&#10;示例：&#10;• 分析 @src/main.js @src/utils.js 中的 #UserManager 类设计&#10;• 为 @components/Button.jsx 生成完整的测试用例&#10;• 重构 @api/auth.js 中的 #validateToken 函数"
                                rows="10"
                            ></textarea>

                            <!-- 生成按钮 - 悬浮在输入框右下角 -->
                            <button id="generateBtn" class="generate-btn-floating">
                                <span class="btn-icon">⚡</span>
                                <span class="btn-text">生成</span>
                            </button>

                            <!-- 自动完成下拉框 - 悬浮定位 -->
                            <div class="autocomplete-dropdown" id="autocompleteDropdown" style="display: none;">
                                <!-- 自动完成选项将在这里动态生成 -->
                            </div>
                        </div>
                    </div>
                </div>

               

                <!-- 消息提示区域 -->
                <div class="message-container" id="messageContainer"></div>
            </div>

            <script src="${scriptUri}"></script>
        </body>
        </html>`;
    }
}

module.exports = ContextEngineViewProvider;
